import time
import types
from google.appengine.api import users
from google.appengine.api import taskqueue
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

class NumCount(db.Model):
    num = db.IntegerProperty()


class Count(webapp.RequestHandler):

    def post(self):
        taskqueue.add(url='/countTask')
        self.redirect('/')

def count(query): 
    i = 0 
    while True: 
        result = query.fetch(5000) 
        i = i + len(result) 
        if len(result) < 5000: 
            break 
        cursor = query.cursor() 
        query.with_cursor(cursor)
 
    numCount = db.GqlQuery('select * from NumCount').get()
    if not isinstance(numCount, types.NoneType):
        numCount.num = i
        numCount.put()
    else:
        numCount = NumCount(num=i)
        numCount.put()


class CountTask(webapp.RequestHandler):

    def post(self):	
	
	gql = 'SELECT __key__ FROM Greeting'

        greeting = db.GqlQuery(gql)
	count(greeting)


